package com.five.admin.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.five.admin.dto.AdminThreadLocalDto;
import com.five.admin.threadLocal.AdminThreadLocal;
import com.five.core.exception.CustomerException;
import com.five.core.result.ResultEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private static final String secret="liutaoshigedashabi";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if (token == null || token.isEmpty() || "null".equals(token)) {
            throw new CustomerException(ResultEnum.TOKEN_IS_NOT_EMPTY);
        }

        String[] split = token.split("\\.");
        if (split.length!=3) {
            throw new CustomerException(ResultEnum.TOKEN_IS_INVALID);
        }

        try {
            if (!JWTUtil.verify(token, secret.getBytes(StandardCharsets.UTF_8))){
                throw new CustomerException(ResultEnum.TOKEN_IS_NOTVERIFY);
            }

            JWT jwt = JWTUtil.parseToken(token);
            Number exp = (Number) jwt.getPayload("exp");
            if (exp.longValue() < System.currentTimeMillis()){
                throw new CustomerException(ResultEnum.TOKEN_IS_EXPIRED);
            }

            //解析token到当前线程中

            String username =(String) jwt.getPayload("username");
            Number id =(Number) jwt.getPayload("id");
            String phone = (String)jwt.getPayload("phone");
            String image =(String) jwt.getPayload("image");

            AdminThreadLocalDto adminThreadLocalDto = new AdminThreadLocalDto();
            adminThreadLocalDto.setUsername(username);
            adminThreadLocalDto.setId(id.longValue());
            adminThreadLocalDto.setPhone(phone);
            adminThreadLocalDto.setImage(image);

            AdminThreadLocal.set(adminThreadLocalDto);
        }catch (Exception e){
            throw new CustomerException(ResultEnum.TOKEN_IS_NOTVERIFY);
        }


        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AdminThreadLocal.remove();
    }
}
